package com.ymttest.business.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.productquery.parameter.ProductDetail.ProductInDetailBean;
import com.ymatou.iapi.productquery.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.selleractivity.service.ApplyActivityCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.AdminCallService;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.business.service.ProductQueryCallService;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class Data201805 {
	// 日志
	private static String logfile = "stgcreateproduct.log";
	// 活动id 固定 activityId 7887
	private static String activityId = "8551";
//	private static String IsolationactivityId = "7913";
	private static String adminuser = "zhouyi";
	private static String adminpwd = "Welcome@123";
	/**
	 * 自动接单
	 */
//	private static String autoactivityId ="8104";

	/**
	 * 创建商品
	 * 
	 * @param data
	 *            sellerid sellername
	 * @param pnum
	 *            创建数量
	 * @return
	 * @throws Exception
	 */
	public static List<Map> createProducts(Integer sellerId, String sellerName, Integer pnum, boolean isIsolation) throws Exception {
		List<Map> mpids = new ArrayList<Map>();

		// 创建商品限制
		// SELECT TOP 1000 [ID]
		// ,[SellerID]
		// ,[ProductPits]
		// ,[CreateTime]
		// ,[LastUpdateTime]
		// FROM [YmtSellerReport].[dbo].[ymt_sellerproductpits] where
		// sellerid=21159026
		Logger.debug("创建商品");

		for (int i = 0; i < pnum; i++) {
			String productId;
			if (isIsolation) {
				productId = ProductManagerCallServiceV2.getStgOneProductId(sellerName, sellerId, 999999);
			} else {
				productId = ProductManagerCallServiceV2.getStgProductId(sellerName, sellerId, 999999,null);
			}
			Thread.sleep(2000);
			Map map = new HashMap<>();
			map.put("productId", productId);
			map.put("sellerId", sellerId);
			map.put("sellerName", sellerName);
			mpids.add(map);
		}
		mpids.forEach(map2 -> {

			String productId = map2.get("productId").toString();
			Logger.debug("查询商品");
			JSONObject prodDetail = new GetProductInfoByProductIdCall().callAndGetReturnData(productId);

			ProductInDetailBean prodBean = null;

			try {
				prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			List<String> catalogList = prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());

			for (String catalog : catalogList) {
				TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalog);
			}

			// TestDataManager.appendFileToLine(logfile, sellerId + ":创建商品:" +
			// productId + ":catalogList:" + catalogList);
			map2.put("catalogList", catalogList);
		});
		return mpids;
	}

	public static List<Map> getProducts(Integer sellerId, String sellerName) throws Exception {
		List<Map> mpids = new ArrayList<Map>();
		List<String> alllist = ProductManagerCallServiceV2.getAllOnSaleProducts(sellerId);
		for (String productId : alllist) {
			JSONObject prodDetail = new GetProductInfoByProductIdCall().callAndGetReturnData(productId);
			ProductInDetailBean prodBean = ProductQueryCallService.getBeanFromJson(prodDetail.getJSONObject("Data").getJSONObject("Product"), ProductInDetailBean.class);
			Logger.debug(FormatUtil.beanToGSONString(prodBean));

			if (prodBean.getCatalogList().size() == 10 && prodBean.getCatalogList().get(0).getPrice().equals(10d)) {

				List<String> catalogList = prodBean.getCatalogList().stream().map(x -> x.getCatalogId()).collect(Collectors.toList());

				for (String catalog : catalogList) {
					TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalog);
				}
				//
				TestDataManager.appendFileToLine(logfile, sellerId + ":" + productId + ":" + catalogList.get(0));

				Map map = new HashMap<>();
				map.put("productId", productId);
				map.put("sellerId", sellerId);
				map.put("sellerName", sellerName);
				map.put("catalogList", catalogList);
				mpids.add(map);
			}
		}
		return mpids;
	}

	/**
	 * 报名审核活动
	 * List<productId sellerId sellerName catalogList>
	 * @throws Exception
	 */
	public static void addActivity(List<Map> mpids) throws Exception {
		Logger.debug("报名活动");
		for (Map map : mpids) {
			String productId = map.get("productId").toString();
			Integer sellerId = Integer.valueOf(map.get("sellerId").toString());
			String sellerName = map.get("sellerName").toString();
			List<String> catalogList = (List<String>) map.get("catalogList");

			ApplyActivityCall activityCall = new ApplyActivityCall();
			JSONObject applyEffectiveActBean = activityCall.getJsonBean(null);
			String applyMsg = "";
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("SellerId", sellerId);
			requestMap.put("ActivityId", activityId);
			requestMap.put("ActivityProducts[0]->ProductId", productId);
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->CatalogId",
			// catalogList.get(0));
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ActivityStockNum",
			// 90000);
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ActivityPrice",
			// 10);
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->Sku", "");
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->BkcKey",
			// "");
			// requestMap.put("ActivityProducts[0]->ApplyCatalogs[0]->ProductInActivityId",
			// 0);

			for (int i = 0; i < catalogList.size(); i++) {
				JSONArray CatalogListBean = applyEffectiveActBean.getJSONArray("ActivityProducts").getJSONObject(0).getJSONArray("ApplyCatalogs");
				CatalogListBean.put(i, new JSONObject(CatalogListBean.get(0).toString()));
				CatalogListBean.getJSONObject(i).put("CatalogId", catalogList.get(i));
				CatalogListBean.getJSONObject(i).put("ActivityStockNum", 90000);
				CatalogListBean.getJSONObject(i).put("ActivityPrice", 10);
				CatalogListBean.getJSONObject(i).put("Sku", "");
				CatalogListBean.getJSONObject(i).put("BkcKey", "");
				CatalogListBean.getJSONObject(i).put("ProductInActivityId", 0);
			}

			JsonBeanHelper.updateJsonBean(applyEffectiveActBean, requestMap);

			activityCall.setData(applyEffectiveActBean);
			Logger.debug("报名");
			activityCall.callService();
			JSONObject ret = new JSONObject(activityCall.getReturnData());
			applyMsg = activityCall.getReturnData();
			// TestDataManager.appendFileToLine(logfile, "catalogList[0]:" +
			// catalogList.get(0) + ":报名活动:" + applyMsg);
			if (ret.has("Data") && ret.getJSONObject("Data").has("ApplySuccessProducts") && ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").length() > 0) {
				JSONArray aslist = ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts");
				for (int i = 0; i < aslist.length(); i++) {
					String inaid = aslist.getJSONObject(i).getString("ProductInActivityId");
					JSONObject jo = AdminCallService.approveProductInActivity(adminuser, adminpwd, inaid,
							MapUtil.hashMap("productBeginTime", YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime", YMTDateUtil.getBeforeOrNextSecond(10 * 60 * 60 * 24)));
					String msgSuccess = "product: " + productId + ",inaid:" + inaid;
					Logger.debug("审核:" + msgSuccess);
				}
				// String inaid =
				// ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").getJSONObject(0).getString("ProductInActivityId");
				// JSONObject jo =
				// AdminCallService.approveProductInActivity(adminuser,
				// adminpwd, inaid,
				// MapUtil.hashMap("productBeginTime",
				// YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime",
				// YMTDateUtil.getBeforeOrNextSecond(10*60*60*24)));
				//
				// String msgSuccess = "product: " + productId + ",inaid:" +
				// inaid;
				//
				//// TestDataManager.appendFileToLine(logfile, "审核:" +
				// msgSuccess);
				// Logger.debug("审核:" + msgSuccess);
			}
		}

	}

	/**
	 * 报名审核活动
	 * 
	 * @throws Exception
	 */
	public static void addIsolationActivity(List<Map> mpids) throws Exception {
		Logger.debug("报名交易隔离活动");
		for (Map map : mpids) {
			String productId = map.get("productId").toString();
			Integer sellerId = Integer.valueOf(map.get("sellerId").toString());
			String sellerName = map.get("sellerName").toString();
			List<String> catalogList = (List<String>) map.get("catalogList");

			ApplyActivityCall activityCall = new ApplyActivityCall();
			JSONObject applyEffectiveActBean = activityCall.getJsonBean(null);
			String applyMsg = "";
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("SellerId", sellerId);
			//这里修改活动
			requestMap.put("ActivityId", activityId);
			requestMap.put("ActivityProducts[0]->ProductId", productId);

			for (int i = 0; i < 1; i++) {
				JSONArray CatalogListBean = applyEffectiveActBean.getJSONArray("ActivityProducts").getJSONObject(0).getJSONArray("ApplyCatalogs");
				CatalogListBean.put(i, new JSONObject(CatalogListBean.get(0).toString()));
				CatalogListBean.getJSONObject(i).put("CatalogId", catalogList.get(i));
				CatalogListBean.getJSONObject(i).put("ActivityStockNum", 90000);
				CatalogListBean.getJSONObject(i).put("ActivityPrice", 10);
				CatalogListBean.getJSONObject(i).put("Sku", "");
				CatalogListBean.getJSONObject(i).put("BkcKey", "");
				CatalogListBean.getJSONObject(i).put("ProductInActivityId", 0);
			}

			JsonBeanHelper.updateJsonBean(applyEffectiveActBean, requestMap);

			activityCall.setData(applyEffectiveActBean);
			Logger.debug("报名");
			activityCall.callService();
			JSONObject ret = new JSONObject(activityCall.getReturnData());
			applyMsg = activityCall.getReturnData();
			// TestDataManager.appendFileToLine(logfile, "catalogList[0]:" +
			// catalogList.get(0) + ":报名活动:" + applyMsg);
			if (ret.has("Data") && ret.getJSONObject("Data").has("ApplySuccessProducts") && ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").length() > 0) {
				JSONArray aslist = ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts");
				for (int i = 0; i < aslist.length(); i++) {
					String inaid = aslist.getJSONObject(i).getString("ProductInActivityId");
					JSONObject jo = AdminCallService.approveProductInActivity(adminuser, adminpwd, inaid,
							MapUtil.hashMap("productBeginTime", YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime", YMTDateUtil.getBeforeOrNextSecond(2 * 60 * 60 * 24)));
					String msgSuccess = "product: " + productId + ",inaid:" + inaid;
					Logger.debug("审核:" + msgSuccess);
				}
				// String inaid =
				// ret.getJSONObject("Data").getJSONArray("ApplySuccessProducts").getJSONObject(0).getString("ProductInActivityId");
				// JSONObject jo =
				// AdminCallService.approveProductInActivity(adminuser,
				// adminpwd, inaid,
				// MapUtil.hashMap("productBeginTime",
				// YMTDateUtil.getBeforeOrNextSecond(300), "productEndTime",
				// YMTDateUtil.getBeforeOrNextSecond(10*60*60*24)));
				//
				// String msgSuccess = "product: " + productId + ",inaid:" +
				// inaid;
				//
				//// TestDataManager.appendFileToLine(logfile, "审核:" +
				// msgSuccess);
				// Logger.debug("审核:" + msgSuccess);
			}
		}

	}

	/**
	 * 创建商品并加入活动
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// 商品数
		int pnum = 100;
		List<String> list = TestDataManager.getLines("data");

		for (String datas : list) {
			Integer sellerId = Integer.valueOf(datas.split(" ")[0]);
			String sellerName = datas.split(" ")[1];
			// List<Map> mpids =
			//创建商品
			List<Map> mpids = Data201805.createProducts(sellerId, sellerName, pnum,true);
			// Thread.sleep(5000);
//			 List<Map> mpids = Data201805.getProducts(sellerId, sellerName);
//			// 下架
//			 for (Map map : mpids) {
//			 String productId=map.get("productId").toString();
//			 List<String> pids=new ArrayList<>();
//			 pids.add(productId);
//			 ProductManagerCallServiceV2.batchSetProductOffSale(pids,sellerId);
//			 }
			//参加活动
			try{
				Data201805.addIsolationActivity(mpids);
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}
